﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.CheckManagement
{
    public partial class AddCheckStandardForm : DevExpress.XtraEditors.XtraForm
    {
        public AddCheckStandardForm()
        {
            InitializeComponent();

            // --- 修复: 删除重复的事件绑定 ---
            // 下面的事件很可能已经在 Designer.cs 文件中由设计器自动绑定过了。
            // 在这里再次绑定会导致事件被触发两次。
            // this.Load += AddCheckStandardForm_Load;
            // this.simpleButton1.Click += simpleButton1_Click;
            // this.checkButton2.Click += checkButton2_Click;
            
            // "取消"按钮的绑定通常不会在设计器里重复，我们保留它
            this.checkButton3.Click += (s, e) => { this.Close(); };
        }

        private async void AddCheckStandardForm_Load(object sender, EventArgs e)
        {
            // --- 新增功能: 从API自动获取检验编码 ---
            using (var client = new HttpClient())
            {
                try
                {
                    var url = "http://localhost:5295/api/CheckStandard/GetCheckItemCode";
                    // 假设API直接返回一个字符串
                    string checkCode = await client.GetStringAsync(url);
                    
                    textEdit1.Text = checkCode.Trim();
                    // 将文本框设为只读，因为编码是系统生成的
                    textEdit1.Properties.ReadOnly = true; 
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("自动获取检验编码失败: " + ex.Message, "API错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    // 如果获取编码失败，禁用提交按钮
                    checkButton2.Enabled = false;
                }
            }
            
            // --- 原有功能: 设置检测项目列表 ---
            // 确保只添加一次操作列
            if (gridView1.Columns["Action"] == null)
            {
                gridControl1.DataSource = itemList;
                if (itemList.Count == 0)
                    itemList.Add(new CheckItemDto() { checkSheetId = textEdit1.Text.Trim() });

                GridColumn actionColumn = new GridColumn();
                actionColumn.Caption = "操作";
                actionColumn.FieldName = "Action";
                actionColumn.Visible = true;
                actionColumn.Width = 80;
                actionColumn.VisibleIndex = gridView1.Columns.Count;

                RepositoryItemButtonEdit buttonEdit = new RepositoryItemButtonEdit();
                buttonEdit.Buttons.Clear();
                buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Plus) { Caption = "+" });
                buttonEdit.Buttons.Add(new EditorButton(ButtonPredefines.Minus) { Caption = "-" });
                buttonEdit.TextEditStyle = TextEditStyles.HideTextEditor;
                buttonEdit.ButtonClick += ButtonEdit_ButtonClick;

                actionColumn.ColumnEdit = buttonEdit;
                gridView1.Columns.Add(actionColumn);
            }
        }

        /// <summary>
        /// 点击"显示工序"按钮，弹出选择窗口并接收返回值
        /// </summary>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            using (var form = new ProcessSelectForm())
            {
                // ShowDialog会暂停当前窗口，直到弹窗关闭
                if (form.ShowDialog(this) == DialogResult.OK)
                {
                    // 如果用户在弹窗里点击了"提交"，就从公共属性获取选择的值
                    // 并填充到你在本窗体上添加的文本框中
                    txtGProcessId.Text = form.SelectedProcessId;
                    txtGProcessName.Text = form.SelectedProcessName;
                }
            }
        }

        /// <summary>
        /// 提交所有数据到API
        /// </summary>
        private async void checkButton2_Click(object sender, EventArgs e)
        {
            // 组装参数
            var param = new AddCheckStandardParam
            {
                checkCode = textEdit1.Text.Trim(),
                checkWay = textEdit2.Text.Trim(),
                checkName = textEdit3.Text.Trim(),
                productCategory = textEdit4.Text.Trim(),
                checkVersion = textEdit5.Text.Trim(), // TODO: 绑定你的检验版本控件

                // 从被弹窗填充的控件中获取工序ID和名称
                gProcessId = txtGProcessId.Text.Trim(),
                gProcessName = txtGProcessName.Text.Trim(),

                isEnabled = checkEdit1.Checked,
                sampleCount = (int)spinEdit1.Value,
                listModel = itemList.ToList()
            };

            // 提交到API
            using (var client = new HttpClient())
            {
                var url = "http://localhost:5295/api/CheckStandard/AddCheckStandard";
                var response = await client.PostAsJsonAsync(url, param);
                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("新增成功！");
                    this.DialogResult = DialogResult.OK; // 通知主窗口刷新
                    this.Close();
                }
                else
                {
                    string msg = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show("新增失败：" + msg);
                }
            }
        }

        private void ButtonEdit_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            int rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle < 0) return;

            if (e.Button.Caption == "+")
            {
                itemList.Insert(rowHandle + 1, new CheckItemDto() { checkSheetId = textEdit1.Text.Trim() });
            }
            else if (e.Button.Caption == "-")
            {
                if (itemList.Count > 1)
                    itemList.RemoveAt(rowHandle);
                else
                    XtraMessageBox.Show("至少保留一行！");
            }
        }

        #region 数据模型
        public class CheckItemDto
        {
            public string checkSheetId { get; set; }
            public string itemName { get; set; }
            public string itemStandard { get; set; }
            public string itemTool { get; set; }
            public string itemDescription { get; set; }
        }
        private BindingList<CheckItemDto> itemList = new BindingList<CheckItemDto>();

        public class AddCheckStandardParam
        {
            public string checkCode { get; set; }
            public string checkName { get; set; }
            public string checkWay { get; set; }
            public string productCategory { get; set; }
            public string checkVersion { get; set; }
            public string gProcessId { get; set; }
            public string gProcessName { get; set; }
            public bool isEnabled { get; set; }
            public int sampleCount { get; set; }
            public List<CheckItemDto> listModel { get; set; }
        }
        #endregion

        // --- 这两个空事件是设计器生成的，保留即可 ---
        private void labelControl2_Click(object sender, EventArgs e) { }
        private void labelControl7_Click(object sender, EventArgs e) { }
    }
}